package com.isias.system.Controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.isias.common.result.Result;
import com.isias.model.dto.CourseDto;
import com.isias.model.dto.UserAndIdDto;
import com.isias.model.dto.VideoDto;
import com.isias.model.system.SysUser;
import com.isias.model.vo.*;
import com.isias.system.Config.WenJianConfig;
import com.isias.system.Service.IAuthenticationFacade;
import com.isias.system.service.CourseService;
import com.isias.system.service.SysUserService;
import com.isias.system.service.VideoService;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin/course/video")
public class VideoController {

    @Autowired
    private CourseService courseService;

    @Autowired
    private VideoService videoService;

    @Autowired
    private IAuthenticationFacade authenticationFacade; //获取当前用户对象类

    @Autowired
    private SysUserService sysUserService;


    @PostMapping("/uploadVideo")
    public Result<Map<String,Object>> coursePicture(MultipartFile file) throws IOException {
        // 文件名称  时间日期+文件名_uuid+后缀
        String fileName = StrUtil.format("{}/{}_{}.{}", DateUtil.format(DateUtil.date(),"yyy/MM/dd"), FilenameUtils.getBaseName(file.getOriginalFilename()),DateUtil.format(new Date(),"yyyyMMdd")+ IdUtil.fastUUID(), FilenameUtils.getExtension(file.getOriginalFilename()));
        // 父目录
        String baseDir = WenJianConfig.getVideoPath();
        //路径拼接
        File desc = new File(baseDir + File.separator + fileName);
        if (!desc.exists())
        {
            if (!desc.getParentFile().exists())
            {
                desc.getParentFile().mkdirs();
            }
        }
        // 下载
        file.transferTo(desc);
        int dirLastIndex = WenJianConfig.getProfile().length() + 1;
        // 截取upload/下的名称存入数据库
        String currentDir = baseDir.substring(dirLastIndex);

        String picture = WenJianConfig.getUrl() + currentDir + "/" + fileName;
        Map<String, Object> map = new HashMap<>();
        // 将头像路径返回
        map.put("VideoUrl",picture);
        return Result.ok(map);
    }


    /**
     * 查询全部，兼条件查询
     * @param videoVo
     * @return
     */
    @GetMapping
    public Result SelectAll(SelectVideoVo videoVo){
        List<VideoDto> dtos = videoService.SelectAll(videoVo);
        return Result.ok(dtos);
    }

    /**
     * 查询单个，主要用于数据回显
     * @param id
     * @return
     */
    @GetMapping("{id}")
    public Result SelectOne(@PathVariable String id){
        VideoDto dtos = videoService.SelectOne(id);
        return Result.ok(dtos);
    }

    /**
     * 插入
     * @param videoVo
     * @return
     */
    @PostMapping
    public Result Insert(@RequestBody VideoVo videoVo){
        //判断从前端传来的数据中是否携带上传者id，如果没有上传者id，则给上传者id赋值为当前用户登录id
        if (videoVo.getUpid()==null||videoVo.getUpid().length()==0){
            videoVo.setUpid(GetId());
        }
        //在数据库中进行添加
        if (videoService.Add(videoVo)) {
            return Result.ok();
        }
        return Result.fail();
    }

    /**
     * 更新
     * @param videoVo
     * @return
     */
    @PutMapping
    public Result Updata(@RequestBody VideoVo videoVo){
        if (videoService.UpdataOneById(videoVo)) {
            return Result.ok();
        }
        return Result.fail();
    }

    /**
     * 删除单个
     * @param id
     * @return
     */
    @DeleteMapping("{id}")
    public Result DeleteOne(@PathVariable String id){
        if (videoService.RemoveOneById(id)) {
            return Result.ok();
        }
        return Result.fail();
    }

    /**
     * 获取所有用户的id和name
     * @return
     */
    @GetMapping("/AllTeacher")
    public Result SelectAllUserAndId(){
        List<UserAndIdDto> list = courseService.SelectUserAndId();
        return Result.ok(list);
    }
    /**
     * 获取当前登录用户的id，虽然听起来很奇怪，但是这个必须要传的，用来鉴权和防止没有填写id导致数据库插入失败
     * @return
     */
    @GetMapping("GetMyId")
    public Result SelectMyId(){
        return Result.ok(GetId());
    }


    /**
     * 获取当前登录用户的id抽取方法
     * @return
     */
    public String GetId(){
        // 获取当前登录用户
        Authentication authentication = authenticationFacade.getAuthentication();
        String username = authentication.getName();
        return sysUserService.GetIdByUsername(username);
    }


}
